<template>
<!-- 批量任务 -->
<a-card :border='false'>
  <div>
    <my-table-screen
      :queryParam="queryParam"
      :queryOptions="queryOptions"
      :queryData="queryData"
      @handleFilter="handleFilter"
    ></my-table-screen>

    <div>
      <my-table
        ref="mytable"
        :tableData="tableData"
        @tableHandleIn="tableHandleIn"
      ></my-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParam.page"
        :limit.sync="queryParam.page_size"
        @pagination="getList"
      />
    </div>
  </div>

  <a-drawer
    placement="right"
    :closable="false"
    :destroyOnClose="true"
    :maskClosable="true"
    width="70%"
    :visible="is_drawer"
    @close="drawerClose"
  >
    <tack-details v-if="is_drawer" :tack_details="tack_details"></tack-details>
  </a-drawer>

  <a-modal
    :title="visibleTitle"
    :confirm-loading="confirmLoading"
    :visible="visible"
    width="50%"
    :maskClosable="false"
    @ok="subimtData"
    @cancel="close"
  >
    <my-form
      ref="myform"
      :formData="formData"
      :formBox="formBox"
      :formOptions="formOptions"
      @subimt="subimt"
    ></my-form>
  </a-modal>

</a-card>
</template>

<script>
import { taskList,taskOpen,taskClose,adUpdateTask,getOceanBatchCreativeList } from "@/api/adv/batch";

const budgetFormBox = {
  rules: {
    budget: [{ required:true, message:'请填写计划预算',trigger:'change' }],
  },
  directions:`为任务内所有计划修改预算，预算幅度不能低于100元（增加或者减少）`,
  formItem:[ 
    { type:'inputNumber',prop:'budget',label:'计划预算',placeholder:"请填写计划预算" }
  ]
}
const bidFormBox = {
  rules: {
    cpa_bid: [{ required:true, message:'请填写计划出价',trigger:'change' }],
  },
  directions:'为任务内所有计划修改出价，修改的出价不能大于当前预算',
  formItem:[ 
    { type:'inputNumber',prop:'cpa_bid',label:'计划出价',placeholder:"请填写计划出价" }
  ]
}

export default {
  components:{
    'tackDetails':()=>import('./tackDetails')
  },
  data () {
    return {
      is_drawer:false,
      tack_details:'',
      // 查询
      queryParam:{  // 初始化数据
        task_type:'OCEAN_AD_CREATIVE_CREATE',
        page:1,
        page_size:10,
      },
      total: 0,
      queryData:[
        { id:'id',title:'ID',type:'input',placeholder:'ID' },
        { id:'task_status',title:'任务状态',type:'select',placeholder:'请选择状态',options:'oceanTaskStatus' },
        // { id:'task_type',title:'任务类型',type:'select',placeholder:'请选择状态',options:'oceanTaskType' },
        { id:'created_at',title:'创建时间',type:'times' },
      ],
      queryOptions:{
        oceanTaskStatus:this.$global.oceanTaskStatus,
        // oceanTaskType:this.$global.oceanTaskType,
      },
      // 表格
      tableData:{
        rowKey:false,
        rowSelection:false,
        tableDataSource:[],
        tableColumns:[
          { title:'ID',dataIndex:'id',align:'center',fixed:'left',width:120 },
          { title:'任务名称',dataIndex:'name',align:'center',fixed:'left',width:200 },
          { title:'任务状态',dataIndex:'task_status',align:'center',fixed:'left',width:120,scopedSlots: {customRender:'filter'},
            formatter:(row)=>{
              for (const item of this.$global.oceanTaskStatus) {
                if( item.value == row.task_status ) return item.label
              }
            },colorEvent:(row)=>{
              if(row.task_status == 'WAITING'){ return `color:${ this.$global.colorStatus['orange'] }` }
              else if(row.task_status == 'RUNNING'){ return `color:${ this.$global.colorStatus['blue'] }` }
              else if(row.task_status == 'DONE'){ return `color:${ this.$global.colorStatus['green'] }` }
              else if(row.task_status == 'CLOSE'){ return `color:${ this.$global.colorStatus['red'] }` }
            }
          },
          { title:'任务类型',dataIndex:'task_type',align:'center',fixed:'left',width:180,scopedSlots: {customRender:'filter'},
            formatter:(row)=>{
              for (const item of this.$global.oceanTaskType) {
                if( item.value == row.task_type ) return item.label
              }
            }
          },
          { title:'操作用户名称',forname:['admin_user','name'],align:'center',width:150,scopedSlots: {customRender:'cycles'},
            "formatter":function(obj,name){
              return obj !== null ? obj[name] : '【系统】'
            }
          },
          { title:'任务总数',forname:['sub_task_count','total'],align:'center',scopedSlots: {customRender:'cycles'},
            "formatter":function(obj,name){
              return obj[name]
            },width:100
          },
          { title:'执行成功',forname:['sub_task_count','SUCCESS'],align:'center',scopedSlots: {customRender:'cycles'},
            "formatter":function(obj,name){
              return obj[name]
            },width:100
          },
          { title:'执行失败',forname:['sub_task_count','FAIL'],align:'center',scopedSlots: {customRender:'cycles'},
            "formatter":function(obj,name){
              return obj[name]
            },colorEvent:(row)=>{
              if( row.sub_task_count.FAIL > 0) return `color:${ this.$global.colorStatus['red'] }`
            },width:100
          },
          { title:'待执行',forname:['sub_task_count','WAITING'],align:'center',scopedSlots: {customRender:'cycles'},
            "formatter":function(obj,name){
              return obj[name]
            },colorEvent:(row)=>{
              if( row.sub_task_count.WAITING > 0) return `color:${ this.$global.colorStatus['orange'] }`
            },width:100
          },
          { title:'创建时间',dataIndex:'created_at',align:'center',width:200 },
          { title:'更新时间',dataIndex:'updated_at',align:'center',width:200 },
          {
            title: '操作',align:'center',fixed:'right',width:250,
            scopedSlots: {customRender: 'action'},
            tableBtn:[
              { title:'详情',type:'primary',btnType:'handleDetails',size:'small' },
              {
                title:'任务', type:'dropdown',dropdown:true,
                children:[
                  { name:'复制该任务',btnType:'handleCopy' },
                  { name:'任务开启',btnType:'handleOpen',iconTitle:true,title:'任务开启，计划继续创建' },
                  { name:'任务关闭',btnType:'handleClose',iconTitle:true,title:'任务关闭，计划停止创建，开启后计划继续创建' },
                ],
              },
              {
                title:'计划', type:'dropdown',dropdown:true,
                children:[
                  { name:'查看计划',btnType:'handleViewAD' },
                  { name:'更改预算',btnType:'changeBudget' },
                  { name:'更改出价',btnType:'changeBid' },
                ],
                children_sub:{
                  children_sub_name:'更改状态',
                  children_sub_item:[
                    { name:'计划开启',btnType:'AdOpen' },
                    { name:'计划关闭',btnType:'AdClose' },
                  ]
                }
              }
            ]
          },
        ]
      },
      // 弹窗
      formData:{},
      formBox:{},
      formOptions:{   //select数据
        putAccount:[],
      },
      visibleTitle:'',
      confirmLoading:false,
      visible:false,
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 初始化数据
    getList(){
      taskList(this.queryParam).then((res)=>{
        if(res.code === 'SUCCESS'){
          this.tableData.tableDataSource = res.data.list
          this.total = res.data.page_info.total
        }
      })
    },
    // table表内列按钮
    async tableHandleIn(tableFnc,row){
      let res
      if( tableFnc === 'handleDetails' ) return ( this.tack_details = row,this.is_drawer = true )  // 详情
      // 任务操作
      if ( tableFnc === 'handleCopy' ){
        const copyRes = await getOceanBatchCreativeList({ task_id:row.id,page:1,page_size:10 })
        let views = copyRes.data.list[0].data.view
        if( views === null ) return this.$Tip('该任务不能复制')
        let routeData = this.$router.resolve({ path: '/batch/create', query: {  data: JSON.stringify( views ) } });
        window.open(routeData.href, '_blank');
        return
      } 
      if ( tableFnc === 'handleOpen' && row.task_status !== 'DONE' ) res = await taskOpen(row.id)
      if ( tableFnc === 'handleClose' && row.task_status !== 'CLOSE' ) res = await taskClose(row.id)
      // 计划操作
      if( tableFnc === 'handleViewAD' ) return this.$router.push( { path:'/promote/plans',query:{ task_id:row.id } } )

      if( tableFnc === 'AdOpen' || tableFnc === 'AdClose' ){
        let quest = {
          ocean_ad_creative_create_task_id:row.id,
          ad_update_type:'STATUS',
          data:{
            opt_status: tableFnc === 'AdOpen' ? 'enable' : 'disable'
          }
        }
        res = await adUpdateTask(quest)
      }

      if( tableFnc === 'changeBudget' || tableFnc === 'changeBid' ){
        this.visibleTitle = tableFnc === 'changeBudget' ? '更改预算' : '更改出价'
        this.formBox = tableFnc === 'changeBudget' ? budgetFormBox : bidFormBox
        this.formData = Object.assign( {},{ id:row.id } )
        this.visible = true
        return
      }
      if( typeof res === 'undefined' ) return this.$Tip('请正确使用按钮')
      this.$Tip(res)
      if( res.code === 'SUCCESS' ) this.getList()
    },
    // 确认
    subimtData(){
      this.$refs.myform.submitForm()
    },
    // 确认提交
    async subimt(formData){
      let quest = {
        ocean_ad_creative_create_task_id:formData.id,
        ad_update_type: this.visibleTitle === '更改预算' ? 'BUDGET' : 'BID',
        data:{ }
      }
      if( this.visibleTitle === '更改预算' ) quest.data.budget = formData.budget 
      if( this.visibleTitle === '更改出价' ) quest.data.bid = formData.cpa_bid 
      const res = await adUpdateTask(quest)
      if( res.code === 'SUCCESS' ) this.$Tip(res),this.visible = false
    },
    close(){
      this.visible = false
    },
    // 搜索
    handleFilter(){
      this.queryParam.page = 1
      this.getList()
    },
    // 关闭抽屉
    drawerClose(){
      this.is_drawer = false
    },
  }
}
</script>
